package net.cloudcodex.client.main.presenter;

import net.cloudcodex.client.CloudCodexEventBus;
import net.cloudcodex.client.main.view.RegisterView;
import net.cloudcodex.client.main.view.RegisterViewImpl;
import net.cloudcodex.client.util.rpc.SuccessCallback;
import net.cloudcodex.shared.dto.Result;
import net.cloudcodex.shared.rpc.HomeRPCAsync;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;

/**
 * 
 * 
 * @author ADaroussin
 */
@Presenter(view = RegisterViewImpl.class)
public class RegisterPresenter extends BasePresenter<RegisterView, CloudCodexEventBus> {

	private final HomeRPCAsync service;

	@Inject
	public RegisterPresenter(HomeRPCAsync pHomeService) {
		this.service = pHomeService;
	}

	@Override
	public void bind() {
		this.view.getValidateButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				register(view.getNickName());
			}
		});
	}

	public void onShowRegisterPopup() {
		view.showPopup();
	}

	private void register(String nickName) {
		service.register(nickName, new SuccessCallback<Result<Boolean>>() {
			@Override
			public void onSuccess(Result<Boolean> result) {
				if (result.isOk() && result.getData()) {
					view.hidePopup();
					eventBus.start();
				} else {
					// TODO: What's happenning here?
				}
			}
		});
	}

}
